#include "qgravitygraphicsitem.h"

#include <QPainter>

#include "qlife.h"

QGravityGraphicsItem::QGravityGraphicsItem ( QGravity* gravity, QColor color ) : QLifeGraphicsItem ( ( QLife* ) gravity )
{
	advance ( 0 );

	// set bounding rect to maximal diameter to avoid ugly graphics
	rect.setX ( -25.5 );
	rect.setY ( -25.5 );
	rect.setWidth ( 51 );
	rect.setHeight ( 51 );

	this -> color = color;
}

QGravityGraphicsItem::~QGravityGraphicsItem()
{}

void QGravityGraphicsItem::advance ( int phase )
{
	if ( phase == 0 )
	{
		setPos ( life -> getX(), life -> getY() );

		// calculate size and color
		float e = life -> getEnergy();

		// e can be beyond it's borders
		if ( e < 0 ) e = 0;
		if ( e > 255 ) e = 255;

		//color = QColor(0, (((int)e * 255) / 150), 0, 128);

		// selection
		if ( isSelected() )
		{
			setPen ( QPen ( color, 4 ) );
			setBrush ( color );
		}
		else
		{
			setPen ( color );
			setBrush ( color );
		}

		e = e / 10;

		visibleRect.setX ( -e );
		visibleRect.setY ( -e );
		visibleRect.setWidth ( 2 * e );
		visibleRect.setHeight ( 2 * e );

		life -> setSelected ( isSelected() );
	}
	else if ( phase == 1 )
	{
		update ( rect );
	}
}

void QGravityGraphicsItem::paint ( QPainter * painter, const QStyleOptionGraphicsItem*, QWidget* )
{
	painter -> setPen ( pen );
	painter -> setBrush ( brush );
	painter -> drawEllipse ( visibleRect );
	painter -> drawText ( ( int ) visibleRect.x(), ( int ) visibleRect.y(), " " );
}
